import logging
import os, pdb
import time

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import JsonResponse

from conf.sysConfig import config
from software.utils import fileStore
from software.models import Software, SoftwareType, SoftwareVersion, SoftwareData
from storehouse.models import Storehouse
from user import dataCheck as da
from user.dataCheck import DataCheck
from user.models import Company, FileStore
from order.models import SoftwareOrder
from software.views.view_download import download

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")


def orderSearch(request, *args, **kwargs):
    """
        url: '/order/screen/',
            method: 'post',
            inputData: {
                token: data.token,//用户密钥
                page: data.page,
                maxItem: data.maxItem,
                warZoneId: data.warZoneId,//战区id 0东 1南 2西 3北 4中
                companyId: data.companyId,//单位id
                softwareName: data.softwareName,//搜索软件名称
                softwareGroup: data.softwareGroup,//0:未处理 1：已处理 2：归档


            },
            resData: {
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null,//检索到总条数
                'orderlist': [{
                    'orderId': null,//订单id
                    'orderNumber': null,//订单号
                    'softwareName': null,//软件名
                    'version': null,//软件版本
                    'warZoneName': null,//软件所属仓库名称
                    'companyName': null,//软件所属单位名称
                    'orderState': null,//0准备中，1:配送中，2：完成
                    'userName': null,//订单创建用户名
                    'createTime': null,//创建时间
                    'delieverType': null,//配送方式

                }]
            }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    # 从数据库获取软件时的filter条件字典
    filterDict = {}

    if requestParam['softwareName'] != '':
        filterDict['softwareVersion__softwareName__icontains'] = requestParam['softwareName']
    if requestParam['softwareGroup'] != '':
        if requestParam['softwareGroup'] == '0':
            filterDict['isExamine'] = False
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '1':
            filterDict['isExamine'] = True
            filterDict['orderUpState'] = '0'
        elif requestParam['softwareGroup'] == '2':
            filterDict['orderUpState'] = '1'
        else:
            data = {
                "code": 1,
                "msg": "softwareGroup Error",
                'totalNum': 0,
                'orderlist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['warZoneId'] != '':
        filterDict['user__warZone__id'] = requestParam['warZoneId']
    if requestParam['companyId'] != '':
        filterDict['user__company__id'] = requestParam['companyId']

    # pdb.set_trace()
    orders = SoftwareOrder.objects.filter(**filterDict).order_by('-createTime')
    orderList = []
    for orderItem in orders:
        item = {
            'orderId': orderItem.id,
            'orderNumber': orderItem.orderNumber,
            'softwareName': orderItem.softwareVersion.softwareName,
            'warZoneName': orderItem.user.warZone.name,
            'companyName': orderItem.user.company.name,
            'version': orderItem.softwareVersion.version,
            'orderState': orderItem.orderState,
            'userName': orderItem.user.name,
            'createTime': orderItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
            'delieverType': orderItem.delieverType,
            'isAgree': orderItem.examineState,
            'iconUrl': download(orderItem.softwareVersion.logo.fileName, 'logo', orderItem.softwareVersion.logo.filePath)[1],
            # 'userPhone': orderItem.user.phone
        }
        orderList.append(item)
    totalNum = len(orderList)
    result = orderList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                requestParam[
                                                                                                    'page'] *
                                                                                                requestParam[
                                                                                                    'maxItem'])]
    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'orderlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)